package com.qf.controller;

import com.github.pagehelper.PageInfo;
import com.qf.entity.Dept;
import com.qf.entity.Employee;
import com.qf.entity.Role;
import com.qf.enums.EmployerExceptionEnum;
import com.qf.service.DeptService;
import com.qf.service.EmployeeService;
import com.qf.service.RoleService;
import com.qf.utils.ExcelUtils;
import com.qf.utils.R;
import com.qf.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/sys")
@Slf4j
public class SysController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;

    @GetMapping("/index")
    public String index(){
        return "redirect:/index.jsp";
    }

    @GetMapping("/list")
    public String list(
            String userName,String roleName,String deptName,
            @RequestParam(defaultValue = "1")Integer pageNum,
            @RequestParam(defaultValue = "5")Integer size,
            Model model
    ){
      PageInfo<Employee> pageInfo = employeeService.selectAll(userName,roleName,deptName,pageNum,size);
      model.addAttribute("userName",userName);
      model.addAttribute("roleName",roleName);
      model.addAttribute("deptName",deptName);
      model.addAttribute("pageInfo",pageInfo);
      return "/resource/demo2/list";
    }

    @GetMapping("/add-ui")
    public String add(Model model){
        List<Dept> deptList = deptService.findAll();
        model.addAttribute(deptList);
        return "/resource/demo2/add";
    }

    @GetMapping("/roles")
    @ResponseBody
    public ResultVO roles(Integer deptId){
     List<Role> roleList= roleService.findDeptById(deptId);
     return R.ok(roleList);
    }

    @PostMapping("/add")
    @ResponseBody
    public ResultVO add(@Valid Employee employee, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【用户管理添加】添加用户失败，msg={}",msg);
            return R.error(EmployerExceptionEnum.USER_PARAM_ERROR.getCode(),msg);
        }
        employeeService.add(employee);
        return R.ok();
    }

    @GetMapping("/updated-ui")
    public String updatedUI(Integer id,Model model){
       Employee employee = employeeService.updatedById(id);
        List<Dept> deptList = deptService.findAll();
        List<Role> roleList = roleService.findDeptById(employee.getDeptId());
        model.addAttribute("employee",employee);
        model.addAttribute("deptList",deptList);
        model.addAttribute("roleList",roleList);
        return "/resource/demo2/updated";
    }
    @PostMapping("/updated")
    @ResponseBody
    public ResultVO updated(@Valid Employee employee, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【用户管理修改】修改用户信息失败，msg={}",msg);
            return R.error(EmployerExceptionEnum.USER_PARAM_ERROR.getCode(),msg);
        }
        employeeService.updated(employee);
        return R.ok();
    }

    @GetMapping("/delete")
    public void delete(Integer id, HttpServletResponse resp){
        Integer count = employeeService.deleteById(id);
        try {
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer =resp.getWriter();
            if(count>0){
                writer.print("<script>alert('删除成功');location.href='sys/list'</script>");
            }else{
                writer.print("<script>alert('删除失败');location.href='sys/list'</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/deletes")
    public void deletes(Integer[] ids, HttpServletResponse resp,String method){
        try {
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            if(method.equals("delete")){
                int count = employeeService.deletes(ids);
                if(count>0){
                    writer.print("<script>alert('删除成功');location.href='/sys/list'</script>");
                }else{
                    writer.print("<script>alert('删除失败');location.href='/sys/list'</script>");
                }
            }else if(method.equals("exports")){
                try {
                    //导出数据
                    //1.查询被选中的数据信息
                    List<Employee> employeeList = employeeService.findEmployeeByIds(ids);
                    //2.导出数据
                    /*设置下载的方式为文件*/
                    resp.setContentType("application/x-download");
                    ExcelUtils.createFirst("用户信息");
                    ExcelUtils.createOthers(employeeList);
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
                    ExcelUtils.export(new FileOutputStream("E://"+(format.format(new Date()))+".xls"));
                    writer.print("<script>alert('导出成功');location.href='/sys/list'</script>");

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
